//
//  ShoppingListVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/25.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import os.log
import AVFoundation
import QRCodeReader

class ShoppingListVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var shoppingLists: [ShoppingList]?
    @IBOutlet weak var tableView: UITableView!
    var edited = false
    
    lazy var readerVC: QRCodeReaderViewController = {
        let builder = QRCodeReaderViewControllerBuilder {
            $0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObject.ObjectType.qr.rawValue], captureDevicePosition: .back)
            $0.showTorchButton = true
            $0.showBottomBt = false
        }
        
        return QRCodeReaderViewController(builder: builder)
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        shoppingLists = loadFile()
        if shoppingLists == nil {
            shoppingLists = [ShoppingList]()
        }
        tableView.contentInset = UIEdgeInsetsMake(44, 0, 66, 0)
        tableView.register(UINib(nibName: "ShoppingListCell", bundle: nil), forCellReuseIdentifier: "ShoppingListCell")
        tableView.delegate = self
        tableView.dataSource = self
        
        let nextBarButton = UIBarButtonItem(title: "下一步", style: .plain, target: self, action: #selector(nextBarBtTapped(_:)))
        navigationItem.setRightBarButtonItems([nextBarButton], animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if edited {
            saveFile { (_) in
                
            }
        }
    }
    
    @IBAction func scanBtTapped(_ button: UIButton!) {
        readerVC.delegate = self
        
        // Or by using the closure pattern
        readerVC.completionBlock = { (result: QRCodeReaderResult?) in
            print(result ?? "")
        }
        
        navigationController?.pushViewController(readerVC, animated: true)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ShoppingListCell") as! ShoppingListCell
        let shopping = shoppingLists![indexPath.row]
        cell.deleteButton.addTarget(self, action: #selector(deleteBtTapped(_:)), for: .touchUpInside)
        cell.nameLabel.text = shopping.materialName
        cell.colorLabel.text = shopping.colorNo + "-" + shopping.color
        cell.numLabel.text = shopping.number
        cell.unitPriceLabel.text = shopping.price
        cell.allPriceLabel.text = "\(Double(shopping.number)! * Double(shopping.price)!)"
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return shoppingLists!.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
    
    @objc func deleteBtTapped(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: tableView)
        guard let indexPath = tableView.indexPathForRow(at: point) else {
            return
        }
        edited = true
        shoppingLists!.remove(at: indexPath.row)
        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
    }
    
    @objc func nextBarBtTapped(_ button: UIBarButtonItem!) {
        guard shoppingLists!.count > 0 else {
            showError(message: "请选择销售物料")
            return
        }
        let proofVC = ShoppingProofVC()
        proofVC.shoppingLists = shoppingLists!
        proofVC.delegate = self
        navigationController?.pushViewController(proofVC, animated: true)
    }
    private func loadFile() -> [ShoppingList]? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: ShoppingList.ArchiveURL.path) as? [ShoppingList]
    }
    
     func saveFile(completeHandler: @escaping (Bool) -> Void) {
        let queue = DispatchQueue(label: "save_file")
        queue.async {
            let isSuccess = NSKeyedArchiver.archiveRootObject(self.shoppingLists!, toFile: ShoppingList.ArchiveURL.path)
            if isSuccess {
                os_log("Successful save file", log: .default, type: .debug)
                DispatchQueue.main.async {
                    completeHandler(isSuccess)
                }
            } else {
                os_log("not successful", log: .default, type: .debug)
                DispatchQueue.main.async {
                    completeHandler(isSuccess)
                }
            }
        }
    }
}

extension ShoppingListVC: ShoppingProofDelegate {
    func didSuccessSale(success: Bool) {
        if success {
            if FileManager.default.fileExists(atPath: ShoppingList.ArchiveURL.path) {
                do {
                    try FileManager.default.removeItem(atPath: ShoppingList.ArchiveURL.path)
                } catch {
                    print(error)
                }
            }
            navigationController?.popViewController(animated: true)
        }
    }
}

extension ShoppingListVC: QRCodeReaderViewControllerDelegate {
    func handleScanCode(message: String) {
        let array = message.components(separatedBy: ":")
        guard array.count > 0, let materialId = Int(array[1]) else { return }
        let detailVC = MainItemDetailVC()
        detailVC.materialId = materialId
        navigationController?.pushViewController(detailVC, animated: true)
    }
    func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
        handleScanCode(message: result.value)
    }
    func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) {
        
    }
    func readerDidCancel(_ reader: QRCodeReaderViewController) {
        reader.stopScanning()
        
    }
}
